package com.itheima.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.cammon.PageInof;
import com.itheima.cammon.ThreadLocalUtil;
import com.itheima.mapper.CategoryMapper;
import com.itheima.pojo.Category;
import com.itheima.service.CategoryService;
import com.itheima.vo.CategoryVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 王同学
 */
@Slf4j
@Service
public class CategoryServiceimpl implements CategoryService {
    @Autowired
    CategoryMapper categoryMapper;
    @Override
    public CategoryVO add(Category category) {
        CategoryVO categoryVO=new CategoryVO();
        //雪花生成菜品id
        String id = IdUtil.getSnowflakeNextIdStr();
        category.setId(id);
        category.setCreateUser("1");
        category.setUpdateUser("1");
        //复制一份给前端的看
        BeanUtils.copyProperties(category,categoryVO);
        categoryMapper.add(category);
        return categoryVO;
    }
    @Override
    public void update(Category category){
        long id = Thread.currentThread().getId();
        log.info("线程{}",id);
        category.setUpdateUser(ThreadLocalUtil.getId());
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.update(category);

    }
    @Override
    public boolean delete(String id){
        Category res = finById(id);
        if (res==null){

            return false;
        }
        int res2 = categoryMapper.delete(id);
        return res2>0;
    }

    @Override
    public PageInof<Category> page(Integer start, Integer pageSize) {
        //分页查询

        //分页查询的响应结果
        //先new一下调用
        PageInof pageInof=new PageInof<Category>();
        //页码长度公式
        Integer page=(start-1)*pageSize;
        List<Category> emp = categoryMapper.page(page, pageSize);
        pageInof.setRecords(emp);
        pageInof.setSize(pageSize);
        pageInof.setCurrent(page);
        return pageInof;
    }

    public Category finById(String Id) {
        LambdaQueryWrapper<Category> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Category::getId,Id);
        //查找这个身份证 如果返回有这个身份证或者null
        Category byId = categoryMapper.getById(Id);
        return byId;
    }

    @Override
    public List<Category> findAll(Integer type){
        return categoryMapper.findAll(type);
    }
}
